package com.lmx.project.controller;

import com.lmx.project.common.BaseResponse;
import com.lmx.project.common.ErrorCode;
import com.lmx.project.common.ResultUtils;
import com.lmx.project.exception.BusinessException;
import com.lmx.project.model.entity.Label;
import com.lmx.project.service.LabelService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author lmx
 * 本类负责有关开设类别的增删改查
 */
@RestController
@RequestMapping("/label")
public class LabelController {
    @Resource
    private LabelService labelService;


    /**
     * 增加标签
     */

    @PostMapping()
    public BaseResponse<Long> addLabel(@RequestBody Label label) {
        if (label.getName() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        boolean save = labelService.save(label);
        if (save) {
            return ResultUtils.success(label.getId());
        } else {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "请联系管理员或稍后重试");
        }
    }

    /**
     * 修改标签
     */

    @PutMapping()
    public BaseResponse<Long> UpdateLabel(@RequestBody Label label) {
        if (label.getId() == null || label.getId() == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (label.getName() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Label byId = labelService.getById(label.getId());
        if (byId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "该标签不存在");
        }
        boolean save = labelService.updateById(label);
        if (save) {
            return ResultUtils.success(label.getId());
        } else {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "请联系管理员或稍后重试");
        }
    }


    /**
     * 删除标签
     */

    @DeleteMapping()
    public BaseResponse<Boolean> deleteLabel(Long id) {
        if (id == null || id == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Label byId = labelService.getById(id);
        if (byId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "该标签不存在");
        }
        boolean b = labelService.removeById(id);
        if (b) {
            return ResultUtils.success(b);
        } else {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "请联系管理员或稍后重试");
        }
    }

    /**
     * 获取全部标签
     */
    @GetMapping
    public BaseResponse<List<Label>> getLabelAll() {
        List<Label> list = labelService.list();
        return ResultUtils.success(list);
    }
}
